package indigoplugin.generators

import io.circe.parser._
import indigoplugin.datatypes.Aseprite
import indigoplugin.IndigoGenerators

object EmbedAseprite {

  def generate(
      moduleName: String,
      fullyQualifiedPackage: String,
      filePath: os.Path
  ): IndigoGenerators.SourceParams => Seq[os.Path] = params => {

    val asepriteJson =
      if (!os.exists(filePath))
        throw new Exception("Aseprite json data file to embed was not found: " + filePath.toString())
      else {
        os.read(filePath)
      }

    val aseprite =
      decode[Aseprite](asepriteJson) match {
        case Right(s) =>
          s

        case Left(e) =>
          throw new Exception(
            "Failed to deserialise json into Aseprite.\nPLEASE NOTE: Aseprite data must be exported using the 'array' option, the 'hash' format is not supported.\n" + e.getMessage
          )
      }

    val wd = params.destination / Generators.OutputDirName

    os.makeDir.all(wd)

    val file = wd / s"$moduleName.scala"

    val contents =
      s"""package $fullyQualifiedPackage
      |
      |import indigo.shared.formats.*
      |
      |// DO NOT EDIT: Generated by Indigo.
      |object $moduleName:
      |
      |  val aseprite: Aseprite =
      |    ${aseprite.render}
      |""".stripMargin

    os.write.over(file, contents)

    Seq(file)
  }

}
